import React, { useEffect, useState } from 'react';
import { Form, Input, InputNumber, Select, Switch, Button } from 'antd';
import { Problem } from '@/types/problem';
import MarkdownEditor from '@/components/MDEditor';
import styles from './BasicForm.module.css';
import SampleList from './SampleList';
import TemplateEditor from './TemplateEditor';
import { languageService } from '@/services/languageService';
import MultiSelector, { SelectableItem } from '@/components/MultiSelector';
import { tagService, Tag } from '@/services/tagService';

const { Option } = Select;

interface BasicFormProps {
  initialValues?: Partial<Problem>;
  onSubmit: (values: Partial<Problem>) => void;
}

// 创建语言项目类型
interface LanguageItem extends SelectableItem {
  name: string;
}

const BasicForm: React.FC<BasicFormProps> = ({ initialValues, onSubmit }) => {
  const [form] = Form.useForm();
  const [allLanguages, setAllLanguages] = useState<LanguageItem[]>([]);
  const [loading, setLoading] = useState(false);

  // 使用useWatch监听languages字段
  const selectedLanguages = Form.useWatch('languages', form);

  // 获取所有支持的语言
  useEffect(() => {
    const fetchLanguages = async () => {
      try {
        setLoading(true);
        const response = await languageService.getLanguages();
        const languageItems: LanguageItem[] = response.data.data.languages.map(lang => ({
          name: lang.name
        }));
        setAllLanguages(languageItems);
        setLoading(false);
      } catch (error) {
        console.error('Failed to fetch languages:', error);
        setLoading(false);
      }
    };
    fetchLanguages();
  }, []);

  // 使用 useEffect 确保表单初始化后再设置值
  useEffect(() => {
    if (initialValues?.samples && Array.isArray(initialValues.samples)) {
      const values = {
        ...initialValues,
        samples: initialValues.samples.map(sample => ({
          input: sample.input,
          output: sample.output
        }))
      };
      form.setFieldsValue(values);
    } else {
      form.setFieldsValue(initialValues);
    }
  }, [form, initialValues]);

  const handleSamplesChange = (samples: any[]) => {
    form.setFieldValue('samples', samples);
  };

  // 标签相关函数
  const fetchTags = async (): Promise<Tag[]> => {
    try {
      return await tagService.getTags();
    } catch (error) {
      console.error('Failed to fetch tags:', error);
      return [];
    }
  };

  const addTag = async (name: string): Promise<Tag> => {
    return await tagService.addTag(name);
  };

  const handleTagChange = (tags: Tag[]) => {
    // 只传递必要的数据
    const simplifiedTags = tags.map(tag => ({
      id: tag.id,
      name: tag.name
    }));
    form.setFieldValue('tags', simplifiedTags);
  };

  // 语言相关函数
  const handleLanguageChange = (languages: LanguageItem[]) => {
    const languageNames = languages.map(lang => lang.name);
    form.setFieldValue('languages', languageNames);
  };

  // 将字符串数组转换为LanguageItem数组
  const convertToLanguageItems = (languageNames: string[] = []): LanguageItem[] => {
    return languageNames.map(name => ({ name }));
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 处理样例数据格式
      if (values.samples) {
        const formattedSamples = values.samples.map((sample: any) => ({
          input: sample.input,
          output: sample.output
        }));
        values.samples = formattedSamples;
      }

      // 处理标签数据格式 - 只保留必要字段
      if (values.tags && Array.isArray(values.tags)) {
        values.tags = values.tags.map((tag: Tag) => ({
          id: tag.id,
          name: tag.name
        }));
      }

      onSubmit(values);
    } catch (error) {
      console.log(error);
      // 表单验证错误会在界面上显示
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      initialValues={{
        visible: true,
        difficulty: 'Mid',
        rule_type: 'ACM',
        time_limit: 1000,
        memory_limit: 256,
        languages: ['C', 'C++', 'Java', 'Python3', 'Golang', 'JavaScript'],
        io_mode: { io_mode: 'Standard IO' },
        template: {},
        tags: [],
        ...initialValues,
      }}
      className={styles.form}
    >
      <div className={styles.formGrid}>
        <Form.Item
          name="_id"
          label="题目ID"
          rules={[{ required: true, message: '请输入题目ID' }]}
        >
          <Input placeholder="例如: A1001" />
        </Form.Item>

        <Form.Item
          name="title"
          label="题目标题"
          rules={[{ required: true, message: '请输入题目标题' }]}
        >
          <Input placeholder="请输入题目标题" />
        </Form.Item>

        <Form.Item
          name="time_limit"
          label="时间限制(ms)"
          rules={[{ required: true }]}
        >
          <InputNumber min={100} max={10000} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="memory_limit"
          label="内存限制(MB)"
          rules={[{ required: true }]}
        >
          <InputNumber min={16} max={1024} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="difficulty"
          label="难度"
          rules={[{ required: true }]}
        >
          <Select>
            <Option value="Low">简单</Option>
            <Option value="Mid">中等</Option>
            <Option value="High">困难</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="rule_type"
          label="题目类型"
          rules={[{ required: true }]}
        >
          <Select>
            <Option value="ACM">ACM</Option>
            <Option value="OI">OI</Option>
          </Select>
        </Form.Item>
      </div>

      <Form.Item
        name="description"
        label="题目描述"
        rules={[{ required: true }]}
      >
        <MarkdownEditor
          height={300}
          placeholder="支持 Markdown 格式..."
        />
      </Form.Item>

      <Form.Item
        name="input_description"
        label="输入说明"
      >
        <MarkdownEditor
          height={200}
          onChange={(value) => value}
          placeholder="请描述输入格式（可选）"
        />
      </Form.Item>

      <Form.Item
        name="output_description"
        label="输出说明"
      >
        <MarkdownEditor
          height={200}
          onChange={(value) => value}
          placeholder="请描述输出格式（可选）"
        />
      </Form.Item>

      <Form.Item
        name="samples"
        label="样例"
        rules={[{ required: true, message: '请至少添加一个样例' }]}
      >
        <SampleList
          onChange={handleSamplesChange}
        />
      </Form.Item>

      <Form.Item
        name="languages"
        label="支持语言"
        rules={[{ required: true, message: '请至少选择一种语言' }]}
        getValueProps={(value) => ({ value: convertToLanguageItems(value) })}
      >
        <MultiSelector<LanguageItem>
          options={allLanguages}
          onChange={handleLanguageChange}
          showAddButton={false}
          addButtonText="添加语言"
          modalTitle="添加新语言"
          inputPlaceholder="请输入语言名称"
        />
      </Form.Item>

      <Form.Item
        name="template"
        label="代码模板"
      >
        <TemplateEditor 
          problemId={initialValues?.id?.toString()} 
          selectedLanguages={selectedLanguages} 
        />
      </Form.Item>

      <Form.Item name="hint" label="提示">
        <MarkdownEditor
          height={200}
          onChange={(value) => value}
          placeholder="可以添加一些解题提示或补充说明，支持 Markdown 格式和数学公式"
        />
      </Form.Item>

      {/* 使用新的MultiSelector组件选择标签 */}
      <Form.Item
        name="tags"
        label="题目标签"
        rules={[{ required: true, message: '请至少选择一个标签' }]}
      >
        <MultiSelector<Tag>
          fetchOptions={fetchTags}
          addItem={addTag}
          onChange={()=>{handleTagChange}}
          addButtonText="添加标签"
          modalTitle="添加新标签"
          inputPlaceholder="请输入标签名称"
        />
      </Form.Item>

      <Form.Item name="source" label="来源">
        <Input />
      </Form.Item>

      <Form.Item name="visible" valuePropName="checked">
        <Switch checkedChildren="公开" unCheckedChildren="私有" />
      </Form.Item>

      <Form.Item className={styles.submitButton}>
        <Button type="primary" onClick={handleSubmit}>
          下一步
        </Button>
      </Form.Item>
    </Form>
  );
};

export default BasicForm; 
